<!--
 * @Description: 供应商管理
 * @Author: wangwangwang
 * @Date: 2020-09-21 14:09:06
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-12-29 14:27:38
-->
<template>
  <div class="pages_content table">
    <el-container>
      <el-header>
        <breaDcrumb />
      </el-header>
      <el-main>
        <div class="header_right" @click="showCardNav = !showCardNav">
          <div class="title">搜索</div>
          <div>
            <transition name="from"></transition>
            <span v-show="!showCardNav">
              <i style="margin-right: 5px" class="el-icon-arrow-down"></i>
            </span>
            <transition name="to"></transition>
            <span v-show="showCardNav">
              <i style="margin-right: 5px" class="el-icon-arrow-up"></i>
            </span>
          </div>
        </div>
        <div v-show="showCardNav" class="hr"></div>
        <el-collapse-transition>
          <div v-show="showCardNav">
            <div class="search">
              <span style="display: inline-block;margin-bottom: 10px;">
                <span style="margin-right: 12px">供应商名称</span>
                <el-input v-model="tableParam.name" style="width: 220px" clearable placeholder="请输入" @keyup.enter.native="gettableData()" />
              </span>
              <span style="margin-left: 24px">
                <span style="margin-right: 12px">供应商类别</span>
                <el-select v-model="tableParam.typeId" style="width: 220px" placeholder="请选择">
                  <el-option v-for="item in typelist" :key="item.id" :label="item.itemName" :value="item.id"></el-option>
                </el-select>
              </span>
              <span style="margin-left: 24px">
                <span style="margin-right: 12px">状态</span>
                <el-select v-model="tableParam.enable" style="width: 220px" placeholder="请选择">
                  <el-option label="全部" :value="''"></el-option>
                  <el-option label="启用" :value="1"></el-option>
                  <el-option label="禁用" :value="0"></el-option>
                </el-select>
              </span>
              <el-button icon="el-icon-search" size="medium" class="bottom_all but1" @click="(tableParam.page = 1), gettableData()">查 询</el-button>
              <el-button size="medium" class="bottom_all_two" style="margin-left: 12px" @click="init()">重 置</el-button>
              <el-button size="medium" class="bottom_all_two" style="margin-left: 12px" @click="tableParamType = true">高级搜索</el-button>
            </div>
          </div>
        </el-collapse-transition>
        <div class="hr"></div>
        <div class="card">
          <div class="card_nav">
            <div>
              <el-button v-if="ButtonList.findIndex(res=>(res.buttonValue=='TIANJIA'))!==-1" size="small" class="bottom_all" style="margin-left: 0" @click="orangeoptionsFun(),addFromDate('添加'),disabledType=false,stations=[]">
                <i class="icon iconfont iconicon_button_add" style="font-size: 12px"></i>
                添加
              </el-button>
              <!-- 	<el-button size="small" class="bottom_two" @click="UpdateOrDelete('update_status', 0)">
								<i class="icon iconfont iconicon_button_delete" style="font-size: 12px;"></i>
								删除
              </el-button>-->
              <el-button v-if="ButtonList.findIndex(res=>(res.buttonValue=='RIYONG'))!==-1" size="small" class="bottom_three" @click="UpdateOrDelete('update_enable', 1)">
                <i class="icon iconfont iconicon_button_startuse" style="font-size: 12px"></i>
                启用
              </el-button>
              <el-button v-if="ButtonList.findIndex(res=>(res.buttonValue=='JINYONG'))!==-1" size="small" class="bottom_four" @click="UpdateOrDelete('update_enable', 0)">
                <i class="icon iconfont iconicon_button_disable1" style="font-size: 12px"></i>
                禁用
              </el-button>
              <el-button v-if="ButtonList.findIndex(res=>(res.buttonValue=='DRGYS'))!==-1" size="small" class="bottom_all_two" style="margin-left: 12px" @click="exportDialog = true">导入供应商</el-button>
              <el-button v-if="ButtonList.findIndex(res=>(res.buttonValue=='PJMBBD'))!==-1" size="small" class="bottom_all_two" style="margin-left: 12px" @click="templateDialog = true, templateData=[]">评价模板绑定</el-button>
              <el-button v-if="ButtonList.findIndex(res=>(res.buttonValue=='PJMBWH'))!==-1" size="small" class="bottom_all_two" style="margin-left: 12px" @click="MTCtemplateDialog = true">评价模板维护</el-button>
            </div>
            <div>
              <el-dropdown :hide-on-click="false" trigger="click" style="margin: 0 20px">
                <el-link :underline="false">
                  <span class="el-icon--left">
                    <i class="iconfont iconicon_button_filtrate"></i>
                  </span>
                  筛选
                </el-link>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item v-for="(item, index) in table" :key="index">
                    <el-checkbox v-model="item.status">{{
                      item.label
                      }}</el-checkbox>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <el-link :underline="false" @click="load()">
                <span class="el-icon--left">
                  <i class="iconfont iconicon_button_export1"></i>
                </span>
                导出
              </el-link>
            </div>
          </div>
          <div v-loading="tableLoading" class="card_info" :style="style">
            <el-table :header-cell-style="{ background: '#f3f6f9' }" :cell-style="{ borderRight: 'none' }" border stripe style="width: 100%" :data="tableData" tooltip-effect="dark" @selection-change="handleSelectionChange">
              <el-table-column align="center" type="selection"></el-table-column>
              <template v-for="(item, index2) in table">
                <el-table-column v-if="item.status" :key="index2" :label="item.label" align="center" :min-width="item.width" :fixed="(item.label =='操作'||item.label == '协作单位')?'right':false">
                  <template slot-scope="scope">
                    <div v-if="item.label == '是否含运输'">
                      <span v-if="scope.row.isCarriage == 0" style="color: #969799">否</span>
                      <span v-else-if=" scope.row.isCarriage == 1 " style="color: #00a754">是</span>
                    </div>
                    <div v-else-if=" item.label == '状态'">
                      <span v-if="scope.row.enable == 0 " style="color: #969799">禁用</span>
                      <span v-else-if="scope.row.enable == 1 " style="color: #00a754">启用</span>
                    </div>
                    <el-button v-else-if="item.label == '协作单位'&&ButtonList.findIndex(res=>(res.buttonValue=='XIEZUODANWEI'))!==-1" size="mini" class="bottom_one" @click="chengecollabor(scope.row)">协作单位</el-button>
                    <div v-else-if="item.label == '操作'">
                      <el-dropdown :hide-on-click="false" trigger="click">
                        <el-button size="mini" class="bottom_one">更多</el-button>
                        <el-dropdown-menu slot="dropdown" style="text-align: left">
                          <el-dropdown-item v-if="ButtonList.some(res=>(res.buttonValue=='XIUGAI'))">
                            <el-button size="mini" style="margin:5px 0" class="bottom_one" @click="pagesupdateFromDate(scope.row, '修改'),disabledType=true">
                              修改
                            </el-button>
                          </el-dropdown-item>
                          <el-dropdown-item v-if="ButtonList.some(res=>(res.buttonValue=='PINGJIA'))">
                            <el-button size="mini" style="margin:5px 0" class="bottom_one" @click="comments(scope.row)">评价
                            </el-button>
                          </el-dropdown-item>
                          <el-dropdown-item v-if="ButtonList.some(res=>(res.buttonValue=='PINGJIAZQ'))">
                            <el-button size="mini" style="margin:5px 0" class="bottom_one" @click="evalua(scope.row)">评价周期
                            </el-button>
                          </el-dropdown-item>
                          <el-dropdown-item>
                            <el-button size="mini" style="margin:5px 0" class="bottom_one" @click="level(scope.row)">合作等级变更
                            </el-button>
                          </el-dropdown-item>
                        </el-dropdown-menu>
                      </el-dropdown>
                    </div>
                    <div v-else-if="item.label == '站点'">
                      {{stationsfile(scope.row.stations)}}
                    </div>
                    <span v-else>{{ scope.row[item.prop] }}</span>
                  </template>
                </el-table-column>
              </template>
            </el-table>
          </div>
          <div class="card_bottom">
            <div class="card_bottom_left">
              <div class="top_page_totle">总共{{ total }}条</div>
              <el-pagination :current-page.sync="tableParam.page" :page-size="tableParam.pageSize" :page-sizes="[10, 20, 30, 40,50,100,200,500,1000]" layout="prev,pager,sizes,next,jumper" :total="total" @size-change="sizeChange" @current-change="gettableData()"></el-pagination>
            </div>
            <div>
              <el-button size="mini" icon="el-icon-refresh-right" class="bottom_all_two" @click="gettableData">刷新</el-button>
            </div>
          </div>
        </div>
      </el-main>
    </el-container>
    <!-- 导入供应商 -->
    <el-dialog v-dialogDrag :visible.sync="exportDialog" width="680px" :close-on-click-modal="false">
      <span slot="title" class="dialog-title">导入供应商</span>
      <div v-loading="loading" element-loading-text="数据解析中..." element-loading-background="rgba(0, 0, 0, 0.8)" class="dialoginfo" style="text-align: center">
        <el-upload class="upload-demo" :on-success="fileSuccess" :before-upload="filebefore" :show-file-list="false" drag action="/icps/system/sign/dataCollection/supplier/importData" name="file" :headers="upheader">
          <i slot="trigger" class="el-icon-upload"></i>
          <div slot="trigger" class="el-upload__text">
            将文件拖到此处，或
            <em>点击选取文件</em>
          </div>
        </el-upload>
        <div style="padding-top: 10px">
          <el-button class="bottom_all" style="margin-left:0" @click="importSubmit()">下载模板</el-button>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="bottom_all_two" @click="exportDialog = false">关 闭</el-button>
      </span>
    </el-dialog>
    <!-- 评价模板维护 -->
    <el-dialog v-dialogDrag :visible.sync="MTCtemplateDialog" width="680px" :close-on-click-modal="false">
      <span slot="title" class="dialog-title">评价模板维护</span>
      <div>
        <div style="padding: 10px 0">
          <span style="margin-right: 12px">评价模板</span>
          <el-select v-model="evalTemplateId" style="width: 200px" clearable @change="changeMTCTemplate">
            <el-option v-for="(item, index) in evalTemplate" :key="index" :label="item.itemName" :value="item.id"></el-option>
          </el-select>
          <span style="margin:0px 12px 0px 12px;">公司名称</span>
          <el-select v-model="companyId" placeholder="请选择" @change="changeMTCTemplate">
            <el-option v-for="item in companyIdlist" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </div>
        <div style="padding: 10px 0">
          <el-button size="mini" class="bottom_all" style="margin-left: 0" @click="additem()">
            <i class="icon iconfont iconicon_button_add" style="font-size: 12px"></i>
            添加
          </el-button>
        </div>
        <el-table :header-cell-style="{ background: '#f3f6f9' }" :cell-style="{ borderRight: 'none' }" border stripe style="width: 100%" :data="MTCTemplate" tooltip-effect="dark">
          <el-table-column label="评价项" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.heading" placeholder="请输入" clearable></el-input>
            </template>
          </el-table-column>
          <el-table-column label="权重" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.ratio" oninput="if(value>100)value=100" type="Number" placeholder="请输入" clearable> <template slot="append">%</template></el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="left" width="120">
            <template slot-scope="scope">
              <el-button size="mini" class="bottom_two" @click="DeleteItem(scope.$index)">
                <i class="icon iconfont iconicon_button_delete" style="font-size: 12px"></i>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="bottom_all_two" @click="MTCtemplateDialog = false">取 消</el-button>
        <el-button class="bottom_all" style="margin-left: 24px" @click="submitMTCTemplate()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 评价模板绑定 -->
    <el-dialog v-dialogDrag :visible.sync="templateDialog" width="680px" :close-on-click-modal="false" :before-close="resetOtherFromDate">
      <span slot="title" class="dialog-title">评价模板绑定</span>
      <div style="padding: 10px 0">
        <div style="padding: 10px 0">
          <span style="margin:0px 12px 0px 12px;">公司名称</span>
          <el-select v-model="companyId" placeholder="请选择" @change="getSupplyEvaluateListFun">
            <el-option v-for="item in companyIdlist" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </div>
        <el-table :header-cell-style="{ background: '#f3f6f9' }" :cell-style="{ borderRight: 'none' }" border stripe style="width: 100%" :data="templateData" tooltip-effect="dark">
          <el-table-column label="供应商类别" align="center" prop="supplierType"></el-table-column>
          <el-table-column label="评价模板" align="center">
            <template slot-scope="scope">
              <el-select v-model="scope.row.supplyEvaluateId" style="width: 100%">
                <el-option v-for="(item, index) in evalTemplate" :key="index" :label="item.itemName" :value="item.id"></el-option>
              </el-select>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="bottom_all_two" @click="resetOtherFromDate">取 消</el-button>
        <el-button class="bottom_all" style="margin-left: 24px" @click="submitTemplate()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加 -->
    <el-dialog v-dialogDrag :visible.sync="addDialog" width="480px" :close-on-click-modal="false" :before-close="resetFromDate">
      <span slot="title" class="dialog-title">{{ addDialogTitle }}</span>
      <div class="dialoginfo">
        <el-form ref="reffromDate" :rules="rules" :inline="true" :model="fromDate" label-width="110px">
          <el-form-item prop="companyId">
            <span slot="label" style="color:  #FF0000 ;">公司</span>
            <el-select ref="selection1" v-model="fromDate.companyId" placeholder="请选择" @change="$nextTick(()=>{fromDate.company = $refs.selection1.selectedLabel})">
              <el-option v-for="item in companyIdlist" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="typeId">
            <span slot="label" style="color: #ff0000">供应商类别</span>
            <el-select v-model="fromDate.typeId" placeholder="请选择" @change="allOrganizationArr=[],fromDate.externalCompanyId='',fromDate.name='',fromDate.externalCompany='',fromDate.organizationIdarr='请选择'">
              <el-option v-for="item in typelist" :key="item.id" :label="item.itemName" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="externalCompanyId">
            <span slot="label" style="color: #ff0000">供应商名称</span>
            <span style="cursor:pointer;min-width: 200px;display: inline-block;" @click.stop="showVisible(true)">{{fromDate.organizationIdarr}}</span>
          </el-form-item>
          <el-form-item>
            <span slot="label">合作等级</span>
            <el-select v-model="fromDate.gradeId" placeholder="请选择" :disabled="disabledType">
              <el-option v-for="item in gradelist" :key="item.id" :label="item.itemName" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="identifying">
            <span slot="label">集团标识</span>
            <el-input v-model="fromDate.identifying" placeholder="请输入" clearable></el-input>
          </el-form-item>
          <el-form-item label="状态" prop="enable">
            <el-radio-group v-model="fromDate.enable">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="bottom_all_two" @click="resetFromDate">取 消</el-button>
        <el-button class="bottom_all" style="margin-left: 24px" @click="psgessubmitFromDate()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 评价 -->
    <el-dialog v-dialogDrag :visible.sync="commentsDialog" width="980px" :close-on-click-modal="false" :before-close="resetOtherFromDate">
      <span slot="title" class="dialog-title">供应商评价</span>
      <div class="title-title">
        <div>当前评价周期：{{ commentsData.period }}</div>
        <div>评价分值：{{ commentsData.evaluateSumScore }}</div>
        <div class="color">
          状态：{{ commentsData.type == 0 ? "未评论" : "已评论" }}
        </div>
      </div>
      <!-- <div style="padding:10px 0px;">
        <span style="margin-left:10px;">
          <span slot="label">站点名称：</span>
          <el-select v-if="commentsData.type == 0" ref="selection22" v-model="fromDate.stationId" @change="$nextTick(()=>{fromDate.stationName = $refs.selection22.selectedLabel})">
            <el-option v-for="item in JSON.parse(keyData.stations)" :key="item.id" :label="item.name||item.stationName" :value="item.id"></el-option>
          </el-select>
          <span v-else style="padding-left:15px">{{commentsData.station}} </span>
        </span>
      </div> -->
      <div style="padding: 0 20px">
        <template v-for="(item, index) in commentsData.list">
          <div :key="index">
            <div class="dialoginfo-title">
              <div class></div>
              <span>{{ item.evaluateTitle }}</span>
              <span style="color: #808080; font-size: 14px">(权重：{{ item.ratio }})</span>
            </div>
            <el-radio-group v-model="item.evaluateOptionId" @change="changeradio">
              <template v-for="(item, index) in stararr">
                <el-radio :key="index" :label="item.id">{{
                  item.text
                  }}</el-radio>
              </template>
            </el-radio-group>
            <el-form label-width="70px" label-position="left" style="width: 820px; padding-top: 20px">
              <el-form-item label="评价">
                <el-input v-model="item.evaluateContent" type="textarea" maxlength="500" :rows="5" resize="none"></el-input>
              </el-form-item>
            </el-form>
          </div>
        </template>
        <div>
          <el-checkbox v-model="checkbox">评价后发送给供应商</el-checkbox>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="bottom_all_two" @click="resetOtherFromDate">取 消</el-button>
        <el-button class="bottom_all" style="margin-left: 24px" :disabled="commentsdisabled" @click="submitcomments()">提交审核</el-button>
      </span>
    </el-dialog>
    <!-- 评价周期 -->
    <el-dialog v-dialogDrag :visible.sync="evaluaDialog" width="680px" :close-on-click-modal="false" :before-close="resetOtherFromDate">
      <span slot="title" class="dialog-title">评价周期</span>
      <div class="checkcycdialoginfo">
        <el-form v-model="evaluaData" :inline="true" label-width="110px">
          <div>
            <el-form-item>
              <span slot="label">当前评价周期</span>
              <span>{{ evaluaText }}</span>
            </el-form-item>
          </div>
          <el-form-item>
            <span slot="label">修改评价周期</span>
            <el-select v-model="evaluaData.evaluateType" placeholder="请选择">
              <el-option label="每月" value="1"></el-option>
              <el-option label="每季度首月" value="2"></el-option>
            </el-select>
            <el-input-number v-model="evaluaData.startDay" size="mini" :controls="false" :min="1" :max="31" style="width:100px;"></el-input-number>
            <span class="text">号</span>
            <span class="text">——</span>
            <el-input-number v-model="evaluaData.endDay" size="mini" :controls="false" :min="1" :max="31" style="width:100px;"></el-input-number>
            <span class="text">号</span>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="bottom_all_two" @click="resetOtherFromDate">取 消</el-button>
        <el-button class="bottom_all" style="margin-left: 24px" @click="submitevalua()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 协作单位 -->
    <el-dialog v-dialogDrag :visible.sync="collaborDialog" width="680px" :close-on-click-modal="false">
      <span slot="title" class="dialog-title">协作单位</span>
      <div>
        <el-button size="mini" class="bottom_all" style="margin-left: 0" @click="addcollabor()">
          <i class="icon iconfont iconicon_button_add" style="font-size: 12px"></i>
          添加
        </el-button>
      </div>
      <div class="dialoginfo">
        <el-table :header-cell-style="{ background: '#f3f6f9' }" :cell-style="{ borderRight: 'none' }" border stripe style="width: 100%" :data="collaborData" tooltip-effect="dark">
          <el-table-column label="协作单位名称" align="center" prop="name"></el-table-column>
          <el-table-column label="操作" align="left" width="200">
            <template slot-scope="scope">
              <el-button v-if="scope.row.type==2" size="mini" class="bottom_two" @click="delcollabor(scope.row)">
                <i class="icon iconfont iconicon_button_delete" style="font-size: 12px"></i>
                删除
              </el-button>
            </template>

          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="bottom_all_two" @click="collaborDialog = false">关 闭</el-button>
        <!-- <el-button class="bottom_all" style="margin-left: 24px" @click="savecollabor()">确 定</el-button> -->
      </span>
    </el-dialog>
    <!-- 高级搜索 -->
    <el-dialog v-dialogDrag :visible.sync="tableParamType" width="650px" :close-on-click-modal="false">
      <span slot="title" class="dialog-title">高级搜索</span>
      <div class="dialoginfo">
        <el-form ref="reftableParam" :inline="true" :model="tableParam" label-width="110px">
          <el-form-item>
            <span slot="label">供应商id</span>
            <el-input v-model="tableParam.code" tplaceholder="请输入" clearable style="width:400px;"></el-input>
          </el-form-item>
          <el-form-item>
            <span slot="label">站点</span>
            <el-input v-model="tableParam.stations" tplaceholder="请输入" clearable style="width:400px;"></el-input>
          </el-form-item>
          <el-form-item>
            <span slot="label">合作等级</span>
            <el-select v-model="tableParam.gradeId" placeholder="请选择" :disabled="disabledType">
              <el-option v-for="item in gradelist" :key="item.id" :label="item.itemName" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="bottom_all_two" @click="tableParamType=false,tableParam.code='',tableParam.stations='',tableParam.gradeId=''">取 消</el-button>
        <el-button class="bottom_all" style="margin-left: 24px" @click="gettableData(),tableParamType=false">搜 索</el-button>
      </span>
    </el-dialog>
    <Organization :TreeLoading="TreeLoading" :default="fromDate.externalSectionId" :visible="organVisible" :dataSource="orangeoptions" :showArr="allOrganizationArr" title="选择组织" @handleSure="handleSure" @handleClose="organVisible=false" />
  </div>
</template>

<script>
import Organization from '@/components/organization';
import mixin from "@/mixins/ICPSmixin.js";
import {
  queryPage,
  batchUpdateOrDelete,
  updateSortNum,
  saveOrUpdate,
  Download,
  updateEvaluateType,
  // supplierEvaluate,
  queryIsEvaluateById,
  queryIsEvaluat,
  OtherDownload,
  getSupplyEvaluateList,
  saveOrUpdateSupplyEvaluateList,
  getSupplyRatingForm,
  saveSupplyRatingForm,
  getRatingFormByTypeId,
  cooperationSaveOrUpdate,
  queryListsByPid,
  deletesCooperation
} from "@/api/GHnumber/supplier.js";
import {
  getDicType,
  getOrganDetail,
  //  getcompany, 
  // getPermissionsUserTree,
  // getOrgznizationTree,
  getOrgznizationTreeByTypeId, 
  permissionsCompanyList, 
} from "@/api/common.js";
import { getUserInfo } from "@/utils/auth.js";
import { getToken, getUserId } from '@/utils/auth';
export default {
  components: {
    Organization
  },
  mixins: [mixin],
  data() {
    return {
      TreeLoading: false,
      tableParamType: false,
      commentsdisabled: false,
      organVisible: false,
      orangeoptions: [],
      orangeoptionsCopy: [],
      UserInfo: '',
      companyIdlist: [],
      companyId: '',
      /*表格增删改查及下载接口*/
      queryPage: queryPage,
      batchUpdateOrDelete: batchUpdateOrDelete,
      updateSortNum: updateSortNum,
      saveOrUpdate: saveOrUpdate,
      DownloadURL: Download,
      /*表格数据*/
      table: [
        { label: "供应商编码", width: "220", prop: "code", status: true },
        { label: "供应商名称", width: "140", prop: "name", status: true },
        { label: "供应商类别", width: "140", prop: "typeName", status: true },
        { label: "集团标识", width: "140", prop: "identifying", status: true },
        { label: "绑定外部公司", width: "140", prop: "externalCompany", status: true },
        { label: "协作单位", width: "120", prop: "", status: true },
        { label: "合作等级", width: "140", prop: "gradeName", status: true },
        { label: "状态", width: "120", prop: "enable", status: true },
        { label: "操作", width: "100", prop: "", status: true },
      ],
      /*表单页类型，0为无树状，1为有树状，有树状在el-main加上display:flex*/
      pagesType: 0,
      /*添加表单数据*/
      rules: {
        companyId: [
          { required: true, message: "请选择公司", trigger: "change" },
        ],
        name: [
          { required: true, message: "请输入供应商名称", trigger: "blur" },
        ],
        typeId: [
          { required: true, message: "请选择供应商类别", trigger: "change" },
        ],
        externalCompanyId: [
          { required: true, message: "请选择外部公司", trigger: "change" },
        ],
        // gradeId: [{ required: true, message: '请选择合作等级', trigger: 'change' }]
      },
      stations: [],
      fromDate: {
        organizationIdarr: '请选择',
        externalCompanyId: '',
        stations: '',
        typeName: "",
        typeId: "",
        gradeName: "",
        gradeId: "",
        isCarriage: 0,
        enable: 1,
        identifying: "",
      },
      typelist: [],
      gradelist: [],
      id: "",
      evaluaDialog: false,
      evaluaText: "",
      evaluaData: {
        evaluateType: '1',
        startDay: "",
        endDay: "",
      },
      /*评价*/
      commentsDialog: false,
      commentsData: {
        supplierId: "", //供应商主键id
        supplierName: "", //供应商名称
        period: "", //周期
        evaluateSumScore: 0,
        pushStatus: 1,
        type: 1, //查询是否评论过返回的是什么就传什么
        list: [],
      },
      checkbox: true,
      stararr: [
        { id: 0, text: "差评（0分）" },
        { id: 40, text: "一星（40分）" },
        { id: 55, text: "二星（55分）" },
        { id: 70, text: "三星（70分）" },
        { id: 85, text: "四星（85分）" },
        { id: 100, text: "五星（100分） " },
      ],
      /*合作等级*/
      // levelDialog: false,
      // levelDate: {
      //   gradeId: "",
      //   gradeName: "",
      // },
      // gradeName: "",
      /*导入数据*/
      exportDialog: false,
      loading: false,
      upheader: {
        "access-token": getToken(),
        "user-id": getUserId(),
      },
      /*评价模板维护*/
      MTCtemplateDialog: false,
      evalTemplateId: "",
      MTCTemplate: [],
      OldMTCTemplate: [],
      /*模板绑定*/
      templateDialog: false,
      templateData: [],
      evalTemplate: [],
      OldtemplateData: [],
      /*协作单位*/
      collaborDialog: false,
      collaborData: [],
      approvalData: [],
      approvalformData: {
        page: 1,
        pageSize: 9,
        supplierId: "",
      },
      approvaltotal: null,
      gradeIdList: [],
      disabledType: false,
      keyData: {
        stations: ''
      },
      allOrganizationArr: []//选中的回显数据
    };
  },
  async created() {
    this.UserInfo = await getUserInfo();
    this.companyIdlist = await permissionsCompanyList()
    console.log(this.companyIdlist);
    /*存储拷贝的原初始化fromDate数据*/
    this.tableParam = { ...this.tableParam, name: "", enable: "", typeId: "", code: '', stations: '', gradeId: '' };
    getDicType({ code: "evalTemplate" }).then((res) => {
      this.evalTemplate = res.data.items;
    });
    getDicType({ code: "supplierType" }).then((res) => {
      this.typelist = res.data.items;
    });
    getDicType({ code: "Levelofcooperation" }).then((res) => {
      this.gradelist = res.data.items;
    });
    this.gettableData();
  },
  /*
   *copy(data)深拷贝数据,返回拷贝完的数据
   *gettableData获取列表数据
   *load下载
   *SortNum保持序列号
   * UpdateOrDelete禁用，启用，删除
   * submitFromDate保存更新数据
   */
  methods: {
    //获取权限外部公司组织树
    async orangeoptionsFun() {
      this.TreeLoading = true
      this.orangeoptions = []
      if (this.orangeoptionsCopy.length != 0) {
        return
      }
      // let orangeoptionsList = await getPermissionsUserTree(true)
      // for (let i = 0; i < orangeoptionsList.length; i++) {
      //   await getOrgznizationTree(orangeoptionsList[i].id).then(async (res) => {
      //     let children = res.data[0].children
      //     orangeoptionsList[i].children = children
      //   })
      // }
      // this.diGui(orangeoptionsList)
      let orangeoptionsList = [];
      const res = await getOrgznizationTreeByTypeId();
      if(res.code === 1001) {
        for (let i = 0; i < res.data.length; i++) {
          orangeoptionsList.push(res.data[i])
        }
      }
      this.orangeoptionsCopy = JSON.parse(JSON.stringify(orangeoptionsList))
      this.TreeLoading = false
      this.diGui(this.orangeoptionsCopy);
      this.$forceUpdate()
    },
    //递归判断是否是子节点,如果要改变数组长度就用反循环
    diGui(arr) {
      if (arr.length > 0) {
        for (let i = arr.length - 1; i >= 0; i--) {
          if (arr[i].organizationType !== 'b8f9367217ab43f8924cd6c08a9ba300') {
            arr[i].disabled = true
          }
          if (arr[i].children != null && arr[i].children.length > 0) {
            arr[i].children.forEach((v) => {
              v.City = arr[i].id
            })
            this.diGui(arr[i].children)
          }
        }
      }
    },
    /**查询父级 */
    handleSure(data) {
      this.organVisible = false;
      const allOrganization = this.getParent(this.orangeoptions, data[0].id);
      this.allOrganizationArr = allOrganization
      if (this.fromDate.typeId == '22069264211120128') {
        console.log(1);
        //内部的
        for (let i = allOrganization.length - 1; i >= 0; i--) {
          if (allOrganization[i].organizationType == '19da56b9e85648059e3cf1e7da497da4') {
            this.fromDate.externalCompanyId = allOrganization[i].id
            break
          }
        }
      } else {
        this.fromDate.externalCompanyId = data[0].id;
      }
      getOrganDetail({id: data[0].id}).then((res) => {
        if (res.code === 1001) {
          this.fromDate.field1 = res.data.shortName
        }
      })
      this.fromDate.externalSectionId = data[0].id;
      this.fromDate.name = allOrganization[allOrganization.length - 1].name;
      this.fromDate.externalCompany = allOrganization.map(item => item.name).join('-');
      this.fromDate.organizationIdarr = allOrganization[allOrganization.length - 1].name;
    },
    //子级查找父级对象
    getParent(data2, nodeId2) {
      var arrRes = [];
      let rev = (data, nodeId) => {
        for (var i = 0, length = data.length; i < length; i++) {
          let node = data[i];
          if (node.id == nodeId) {
            arrRes.unshift(node);
            //City父级id
            rev(data2, node.City);
            break;
          } else {
            if (node.children) {
              rev(node.children, nodeId);
            }
          }
        }
        return arrRes;
      };
      arrRes = rev(data2, nodeId2);
      return arrRes;
    },
    async showVisible(type) {
      if (!this.fromDate.typeId) {
        this.$message({
          message: "请选择供应商类别！",
          type: "warning",
        });
        return
      }
      if (this.fromDate.typeId == '22069264211120128') {
        //只要内部公司
        let arr = [];
        const res = await getOrgznizationTreeByTypeId();
        if(res.code === 1001) {
          for (let i = 0; i < res.data.length; i++) {
            arr.push(res.data[i])
          }
        }
        // await this.orangeoptionsCopyDiGuiNeiBu(arr, 'b8f9367217ab43f8924cd6c08a9ba300', 0)//这里传外部id做筛选
        this.orangeoptions = arr
      } else {
        //只要外部公司
        let arr = JSON.parse(JSON.stringify(this.orangeoptionsCopy))
        await this.orangeoptionsCopyDiGui(arr, 'b8f9367217ab43f8924cd6c08a9ba300')
        this.orangeoptions = arr
        console.log(this.orangeoptions)
      }
      if (type) {
        this.organVisible = true;
        if (this.allOrganizationArr.length > 0) {//选中的回显自定义颜色
          this.allOrganizationArr = this.allOrganizationArr.map(res => (res.id))
        }
      }
      this.TreeLoading = false
    },
    //筛选出外部单位的新数组对象
    orangeoptionsCopyDiGui(arr, organizationType) {
      if (arr.length > 0) {
        for (let i = arr.length - 1; i >= 0; i--) {
          // arr[i].disabled = !arr[i].disabled;
          if (arr[i].children != null && arr[i].children.length > 0) {
            arr[i].children.forEach((v) => {
              v.City = arr[i].id
            })
            this.orangeoptionsCopyDiGui(arr[i].children, organizationType)
          }
          // if (arr[i].organizationType == organizationType) {
          //   arr[i].disabled = false
          //   if (arr[i].children != null && arr[i].children.length > 0) {
          //     arr[i].children.forEach((v) => {
          //       v.City = arr[i].id
          //     })
          //     this.orangeoptionsCopyDiGui(arr[i].children, organizationType)
          //   }
          // } else {
          //   arr.splice(i, 1)
          // }
        }
      }
    },
    //筛选出内部单位的新数组对象
    orangeoptionsCopyDiGuiNeiBu(arr, organizationType, size) {
      if (arr.length > 0) {
        for (let i = arr.length - 1; i >= 0; i--) {
          if (size == 0) {
            if (arr[i].organizationType != '19da56b9e85648059e3cf1e7da497da4') {
              //如果不是内部就删除掉
              arr.splice(i, 1)
            } else {
              arr[i].disabled = false
              if (arr[i].children != null && arr[i].children.length > 0) {
                arr[i].children.forEach((v) => {
                  v.City = arr[i].id
                })
                size++
                this.orangeoptionsCopyDiGuiNeiBu(arr[i].children, organizationType, size)
              }
            }
          } else {
            if (arr[i].organizationType == organizationType) {
              //如果是外部就删除掉，其他的不管
              arr.splice(i, 1)
            } else {
              arr[i].disabled = false
              if (arr[i].children != null && arr[i].children.length > 0) {
                arr[i].children.forEach((v) => {
                  v.City = arr[i].id
                })
                size++
                this.orangeoptionsCopyDiGuiNeiBu(arr[i].children, organizationType, size)
              }
            }
          }
        }
      }
    },
    stationsfile(low) {
      if (low) {
        let txt = JSON.parse(low).map(res => (res.name)).join(',')
        return txt
      }
    },
    async pagesupdateFromDate(a, b) {
      await this.updateFromDate(this.fromDate, b)
      await this.orangeoptionsFun()
      this.fromDate = this.copy(a)
      this.fromDate.organizationIdarr = a.externalCompany
      if (!a.externalSectionId) {
        a.externalSectionId = a.externalCompanyId
      }
      await this.showVisible()
      await this.handleSure([{ id: a.externalSectionId }])
    },
    /*评价模板维护*/
    additem() {
      if (this.evalTemplateId == "") {
        this.$message({
          message: "警告哦，请先选择评价模板",
          type: "warning",
        });
        return;
      }
      let item = {
        template: this.$fromatTable(
          this.evalTemplate,
          this.evalTemplateId,
          "id",
          "itemName"
        ),
        templateId: this.evalTemplateId,
        heading: "",
        ratio: "",
        type: 1,
      };
      console.log(item);
      this.MTCTemplate.push(item);
    },
    DeleteItem(index) {
      this.MTCTemplate.splice(index, 1);
    },
    changeMTCTemplate() {
      getSupplyRatingForm({ templateId: this.evalTemplateId, companyId: this.companyId }).then((res) => {
        this.OldMTCTemplate = this.copy(res.data);
        this.MTCTemplate = res.data.map((res) => {
          let obj = new Object();
          obj.id = res.id;
          obj.template = res.template;
          obj.templateId = res.templateId;
          obj.ratio = res.ratio;
          obj.heading = res.heading;
          obj.type = 2;
          return obj;
        });
        console.log(res.data);
      });
    },
    submitMTCTemplate() {
      let allHasData = this.MTCTemplate.filter((item) =>
        this.OldMTCTemplate.some((items) => item.id == items.id)
      );
      let deleteData = this.OldMTCTemplate.filter(
        (item) => !allHasData.some((items) => item.id == items.id)
      );
      deleteData.forEach((res) => {
        res.type = 0;
      });
      let addData = this.MTCTemplate.filter(
        (item) => !allHasData.some((items) => item.id == items.id)
      );
      let arr = [...allHasData, ...deleteData, ...addData];
      arr.forEach((res) => {
        res.companyId = this.companyId
      })
      saveSupplyRatingForm(arr).then((res) => {
        if (res.data) {
          this.MTCtemplateDialog = false;
          this.evalTemplateId = "";
          this.MTCTemplate = [];
          this.OldMTCTemplate = [];
          this.companyId = ''
          this.$message.success('设置成功');
        } else {
          this.$message({
            message: "警告，权重比超出，请修改",
            type: "warning",
          });
        }
      });
    },
    getSupplyEvaluateListFun() {
      getSupplyEvaluateList({ companyId: this.companyId }).then((res) => {
        this.OldtemplateData = this.copy(res.data);
        this.templateData = this.typelist.map((item) => {
          let obj = new Object();
          obj.supplyEvaluate = "";
          obj.supplyEvaluateId = "";
          obj.supplierType = item.itemName;
          obj.supplierTypeId = item.id;
          obj.type = 1;
          for (let a in res.data) {
            if (res.data[a].supplierTypeId == item.id) {
              obj.id = res.data[a].id;
              obj.supplyEvaluate = res.data[a].supplyEvaluate;
              obj.supplyEvaluateId = res.data[a].supplyEvaluateId;
              obj.type = 2;
            }
          }
          return obj;
        });
        this.templateDialog = true;
      });
    },
    submitTemplate() {
      let allHasData = this.templateData.filter((item) =>
        this.OldtemplateData.some((items) => item.id == items.id)
      );
      let deleteData = this.OldtemplateData.filter(
        (item) => !allHasData.some((items) => item.id == items.id)
      );
      deleteData.forEach((res) => {
        res.type = 0;
      });
      let addData = this.templateData.filter(
        (item) => !allHasData.some((items) => item.id == items.id)
      );
      let arr = [...allHasData, ...deleteData, ...addData];
      arr.map((res) => {
        res.companyId = this.companyId
      })
      saveOrUpdateSupplyEvaluateList(arr).then(() => {
        this.templateDialog = false;
        this.companyId = ''
      });
    },
    /*协作单位*/
    chengecollabor(low) {
      this.id = low.id;
      this.collaborData = [];
      queryListsByPid({ supplierId: this.id }).then((res) => {
        this.collaborData = res.data;
      });
      this.collaborDialog = true;
    },
    delcollabor(low) {
      deletesCooperation({ id: low.id }).then(res => {
        if (res.code == 1001) {
          this.$message({
            message: '删除成功',
            type: 'success'
          });
          queryListsByPid({ supplierId: this.id }).then((res) => {
            this.collaborData = res.data;
          });
        }
      })
      console.log(low)
    },
    addcollabor() {
      this.$prompt("", "输入协作单位名称", {
        confirmButtonText: "提交",
        cancelButtonText: "取消",
        cancelButtonClass: "bottom_all_two",
        confirmButtonClass: "bottom_all",
        closeOnClickModal: false,
        inputValidator: (val) => {
          if (val == "" || val == null) {
            return "名称不能为空";
          }
        },
      })
        .then(({ value }) => {
          const item = [
            {
              name: value,
              supplierId: this.id,
            },
          ];
          cooperationSaveOrUpdate(item).then(() => {
            queryListsByPid({ supplierId: this.id }).then((res) => {
              if (res.code == 1001) {
                this.collaborData = res.data;
                this.$message({
                  message: '添加成功',
                  type: 'success'
                });
              }

            });
          });
        })
        .catch(() => { });
    },
    /*导入数据*/
    filebefore(file) {
      this.loading = true;
      const isJPG = file.type === 'application/vnd.ms-excel';
      if (!isJPG) {
        this.$message.error('数据上传必须是 xls 格式!');
        this.loading = false
      }
      return isJPG;
    },
    fileSuccess(res) {
      this.loading = false;
      if (res.code == 1001) {
        this.$message({
          dangerouslyUseHTMLString: true,
          message: `本次导入数据成功${res.data.successNum}条，失败<span style="color:red">${res.data.failureNum}</span>条！！！`,
          type: 'success'
        });
        if (res.data.failureNum !== 0) {
          let text = res.data.errResult.map(res => (res.name + '-' + res.reason)).join(',')
          this.$notify.error({
            title: '导入失败用户',
            message: text,
            duration: 0
          });
        }
        if (res.data.successNum !== 0) {
          this.init()
        }
      } else {
        this.$message.error(res.codeMsg);
      }
    },
    importSubmit() {
      this.$Download(OtherDownload);
    },
    init() {
      /*重置数据*/
      this.tableParam.name = "";
      this.tableParam.enable = "";
      this.tableParam.typeId = "";
      this.tableParam.code = "";
      this.tableParam.stations = "";
      this.tableParam.gradeId = "";
      this.gettableData();
    },
    psgessubmitFromDate() {
      this.$refs.reffromDate.validate((valid) => {
        if (valid) {
          this.fromDate.typeName = this.$fromatTable(
            this.typelist,
            this.fromDate.typeId,
            "id",
            "itemName"
          );
          this.fromDate.gradeName = this.$fromatTable(
            this.gradelist,
            this.fromDate.gradeId,
            "id",
            "itemName"
          );
          this.submitFromDate();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    evalua(data) {
      this.id = data.id;
      this.evaluaText = "暂未设置";
      if (data.evaluateType) {
        this.evaluaText =
          (data.evaluateType == 1 ? "每月" : "每季度") +
          data.startDay +
          "号" +
          " " +
          "--" +
          " " +
          data.endDay +
          "号";
      }
      this.evaluaDialog = true;
      if (data.startDay) {
        this.evaluaData.startDay = data.startDay
        this.evaluaData.endDay = data.endDay
      }
    },
    submitevalua() {
      if (
        this.evaluaData.startDay == "" ||
        this.evaluaData.endDay == ""
      ) {
        this.$message({
          message: "警告哦，请填写信息完整后再保存",
          type: "warning",
        });
        return;
      }
      updateEvaluateType({ ...this.evaluaData, id: this.id }).then(() => {
        this.evaluaDialog = false;
        this.gettableData();
        this.evaluaData = {};
      });
    },
    async comments(data) {
      this.keyData = data;
      this.commentsData.list = []
      this.commentsData.supplierId = data.id;
      this.commentsData.supplierName = data.name;
      this.commentsData.evaluateSumScore = 0;
      await queryIsEvaluateById({ id: data.id }).then((res) => {
        if (!res.data) {
          this.commentsdisabled = true
          this.commentsData.period = '暂无评价周期/暂时不在评价周期内'
          this.commentsData.type = 0;
          return
        }
      });
      if (!this.commentsdisabled) {
        await queryIsEvaluat({ supplierId: data.id }).then((res) => {
          this.commentsData.period = res.data.period;
          this.commentsData.type = res.data.type; //1 已评论就不能在评论  。0未评论可以评论
          if (res.data.type == 1) {
            this.commentsData.company = res.data.evaluate.company
            this.commentsData.station = res.data.evaluate.station
            this.commentsData.list = res.data.list.map(res => {
              let obj = new Object();
              obj.evaluateTitle = res.evaluateTitle;
              obj.ratio = res.ratio;
              obj.evaluateOptionId = Number(res.evaluateOptionId);
              obj.evaluateOptionScore = res.evaluateOptionScore;
              obj.evaluateContent = res.evaluateContent;
              return obj;
            })
            this.commentsdisabled = true
            this.commentsDialog = true;
          }
        });
      }
      if (this.commentsData.type == 0) {
        this.commentsDialog = true;
        getRatingFormByTypeId({ supplierTypeId: data.typeId, companyId: data.companyId }).then(
          (res) => {
            this.commentsData.list = res.data.map((res) => {
              let obj = new Object();
              obj.evaluateTitle = res.evaluateTitle;
              obj.ratio = res.ratio;
              obj.evaluateOptionId = 0;
              obj.evaluateOptionScore = "";
              obj.evaluateContent = "";
              return obj;
            });
            this.commentsDialog = true;
            console.log(this.commentsData.list);
          }
        )
      }

    },
    changeradio() {
      let num = 0;
      this.commentsData.list.forEach((item) => {
        item.evaluateOptionScore = this.$fromatTable(
          this.stararr,
          item.evaluateOptionId,
          "id",
          "text"
        );
        num = num + item.ratio * item.evaluateOptionId;
      });
      this.commentsData.evaluateSumScore = num / 100;
    },
    submitcomments() {
      // if (this.fromDate.stationId) {
      let _this = this;
      _this.commentsData.pushStatus = _this.checkbox ? 1 : 0;
      _this.commentsData.companyId = this.keyData.companyId
      _this.commentsData.company = this.keyData.company
      _this.commentsData.stationId = this.fromDate.stationId
      _this.commentsData.stationName = this.fromDate.stationName;
      _this.commentsData.list = JSON.stringify(_this.commentsData.list);
      // supplierEvaluate(_this.commentsData).then((res) => {
      //   _this.commentsDialog = false;
      //   _this.commentsdisabled = false
      // });
      this.commentsDialog = false;
      this.$router.push({ name: 'SupplierRating', query: { ..._this.commentsData, type: 1, id: this.keyData.id, supplierTypeId: this.keyData.typeId } });
      // } else {
      //   this.$message({
      //     message: '站点不能为空',
      //     type: 'warning'
      //   });
      // }
    },
    level(data) {
      const query = {
        type: 1,
        company: data.company,
        companyId: data.companyId,
        stations: data.stations,
        name: data.name,
        typeName: data.typeName,
        typeId: data.typeId,
        gradeName: data.gradeName,
        gradeId: data.gradeId,
        id: data.id,
      }
      this.$router.push({ name: 'ChangeLevelCoop', query });
    },
    resetOtherFromDate() {
      this.evaluaDialog = false;
      this.commentsDialog = false;
      this.levelDialog = false;
      this.templateDialog = false;
      this.commentsdisabled = false
      this.companyId = ''
      this.levelDate = {
        gradeId: "",
        gradeName: "",
      };
    },
    sizeChange(value) {
      this.tableParam.pageSize = value;
      this.gettableData();
    },
  },
};
</script>

<style lang="scss" scoped>
.title-title {
  @include discen_al;
  justify-content: space-between;
  font-size: 16px;
  font-weight: bold;
  color: #000000;
  line-height: 40px;
  .color {
    color: $bg_color;
  }
}
.el-radio {
  line-height: 45px;
}
.dialoginfo-title {
  display: flex;
  align-items: center;
  height: 50px;
  > div {
    width: 4px;
    height: 20px;
    background: $bg_color;
  }
  > span {
    padding-left: 10px;
    font-size: 20px;
    color: $bg_color;
    font-weight: 600;
  }
}
.table_link {
  margin-left: 10px;
  color: $bg_color;
}

.table_link:hover {
  opacity: 0.7;
}
.el-input,
.el-select {
  width: 200px;
}
.dialoginfo {
  .el-input,
  .el-select {
    width: 280px;
  }
}
.dialogOtherinfo {
  .el-input,
  .el-select {
    width: 310px;
  }
}
.checkcycdialoginfo {
  .el-input {
    width: 100px;
  }
  .el-select {
    width: 100px;
    margin-right: 20px;
  }
  .text {
    padding: 10px;
  }
}
</style>
